package com.sergio.accounting.controller;

import com.sergio.accounting.dto.ApiResponse;
import com.sergio.accounting.entity.User;
import com.sergio.accounting.service.UserService;
import com.sergio.accounting.util.JwtDebugUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@CrossOrigin
public class AuthController {

    private final UserService userService;
    private final JwtDebugUtil jwtDebugUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@RequestBody @Valid LoginRequest request) {
        try {
            String token = userService.login(request.getUsername(), request.getPassword());
            User user = userService.findByUsername(request.getUsername());
            
            // 调试：分析生成的token
            log.info("用户 {} 登录成功，生成token长度: {}", request.getUsername(), token.length());
            jwtDebugUtil.analyzeToken(token, "SquirrelSave-secret-key-2024"); // 临时硬编码，实际应该从配置读取
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", user);
            
            return ApiResponse.success("登录成功", result);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<User> register(@RequestBody @Valid RegisterRequest request) {
        try {
            User user = userService.register(
                request.getUsername(),
                request.getPassword(),
                request.getEmail(),
                request.getNickname()
            );
            return ApiResponse.success("注册成功", user);
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 刷新JWT token
     */
    @PostMapping("/refresh")
    public ApiResponse<Map<String, Object>> refreshToken(@RequestHeader("Authorization") String authorization) {
        try {
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                return ApiResponse.error("无效的token");
            }
            
            String token = authorization.substring(7);
            String newToken = userService.refreshToken(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", newToken);
            result.put("message", "token刷新成功");
            
            return ApiResponse.success("token刷新成功", result);
        } catch (Exception e) {
            log.error("token刷新失败: {}", e.getMessage());
            return ApiResponse.error("token刷新失败");
        }
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    public ApiResponse<String> logout(@RequestHeader("Authorization") String authorization) {
        try {
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                return ApiResponse.success("退出成功");
            }
            
            String token = authorization.substring(7);
            // 这里可以添加token到黑名单的逻辑
            // 目前JWT是无状态的，所以直接返回成功即可
            log.info("用户退出登录，token: {}", token.substring(0, Math.min(20, token.length())) + "...");
            
            return ApiResponse.success("退出成功", "退出成功");
        } catch (Exception e) {
            log.error("退出登录失败: {}", e.getMessage());
            return ApiResponse.error("退出失败");
        }
    }

    /**
     * 登录请求DTO
     */
    public static class LoginRequest {
        private String username;
        private String password;

        // Getters and Setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }

    /**
     * 注册请求DTO
     */
    public static class RegisterRequest {
        private String username;
        private String password;
        private String email;
        private String nickname;

        // Getters and Setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
    }
}
